//
//  AppleSubscriptions.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/3/26.
//
import Vapor
import AppStoreServerLibrary
import AsyncHTTPClient
struct AppStoreConfiguration {
    static let bundleId = "com.xusi1508tracker.www" // 你的应用 bundle ID
    static let keyIdentifier = "HXL4GW4W9D" // 例如 "ABC123DEFG"
    static let issuerId = "7ef117b7-2953-4df9-999e-8eeb54a35521" // 例如 "12345678-90ab-cdef-1234-567890abcdef"
    static let environment = AppStoreEnvironment.production // 或 .sandbox 用于测试
    static let privateKey = """
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgkUwnxhzFa9mmixJt
oUR6NmXY/vCVgLjNZDu62SWy6MigCgYIKoZIzj0DAQehRANCAATVkBnYOOSD2EoS
WYSuUtQ9BOkaSvp597UFl9+W3mqs5qwGiq+4Vlm7sbfMVqkhon7vkUVkR0mnH6Xt
5ivgkMSE
-----END PRIVATE KEY-----
"""
}

struct AppStoreService {
    
    let certPaths: [String]
    
    init(certPaths: [String]) {
        self.certPaths = certPaths
    }
    
    func getTest() async {
        let sandBoxStr = Environment.get("SanxBox") ?? "0"
        let sandBox = sandBoxStr == "1"
        let client = try! AppStoreServerAPIClient(signingKey: AppStoreConfiguration.privateKey, keyId: AppStoreConfiguration.keyIdentifier, issuerId: AppStoreConfiguration.issuerId, bundleId: AppStoreConfiguration.bundleId, environment: sandBox ? AppStoreEnvironment.sandbox : AppStoreEnvironment.production)
        let response = await client.requestTestNotification()
        print(response)
    }
    
    func handleSubscriptionChange(jwt: String) async throws -> ResponseBodyV2DecodedPayload {
        let datas = self.certPaths.map { path in
            let data = try! Data(contentsOf: URL(fileURLWithPath: path))
            return data
        }
        let sandBoxStr = Environment.get("SanxBox") ?? "0"
        let sandBox = sandBoxStr == "1"
        let verifier = try SignedDataVerifier(rootCertificates: datas, bundleId: AppStoreConfiguration.bundleId, appAppleId: 6742769723, environment: sandBox ? AppStoreEnvironment.sandbox : AppStoreEnvironment.production, enableOnlineChecks: false)
        let result = await verifier.verifyAndDecodeNotification(signedPayload: jwt)
        switch result {
        case .valid(let payload):
            return payload
        case .invalid(let error):
            print(error)
            throw NSError(domain: "解析失败", code: -1, userInfo: nil)
        }
    }
    
    func extractOrderTransaction(signedInfo: String) async throws -> JWSTransactionDecodedPayload {
        let datas = self.certPaths.map { path in
            let data = try! Data(contentsOf: URL(fileURLWithPath: path))
            return data
        }
        let sandBoxStr = Environment.get("SanxBox") ?? "0"
        let sandBox = sandBoxStr == "1"
        let verifier = try SignedDataVerifier(rootCertificates: datas, bundleId: AppStoreConfiguration.bundleId, appAppleId: 6742769723, environment: sandBox ? AppStoreEnvironment.sandbox : AppStoreEnvironment.production, enableOnlineChecks: false)
        let result = await verifier.verifyAndDecodeTransaction(signedTransaction: signedInfo)
        switch result {
        case .valid(let payload):
            return payload
        case .invalid(let error):
            print(error)
            throw NSError(domain: "解析失败", code: -1, userInfo: nil)
        }
    }
}

extension Application {
    struct AppStoreKey: StorageKey {
        typealias Value = AppStoreService
    }
    
    var appstore: AppStoreService {
        get { storage[AppStoreKey.self]! }
        set { storage[AppStoreKey.self] = newValue }
    }
}
